import time
import uuid
import requests
from django.shortcuts import render
from django.http import JsonResponse,HttpResponseRedirect
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
from . models import *
from .sers import *

# Create your views here.
# class DingdingUrl(APIView):
#     def get(self,request):
#         redirect_url = 'http://127.0.0.1:8000/ddcallback/'
#         client_id = 'ding0trlgklqrivkmcjc'
#         url = "http://login.dingtalk.com/oauth2/auth?redirect_url=%s&client_id=%scope=openid&state=dddd&prompt=consent"%(redirect_url,client_id)
#         return Response({'code':200,'url':url})

class DingTalkLogin(APIView):
    def get(self, request):
        from urllib.parse import quote
        params = [
            f"redirect_uri={quote('http://127.0.0.1:8000/user/dingtalkCallback/')}",
            "response_type=code",
            "client_id=ding0trlgklqrivkmcjc",
            "scope=openid",
            "prompt=consent"
        ]
        url = "https://login.dingtalk.com/oauth2/auth?" + ("&".join(params))
        return Response({"url": url})





    # 钉钉回调接口

class DingTalkCallback(APIView):
    def get(self, request):
        authCode = request.query_params.get('code')
        print(authCode)

        # 根据authCode获取用户accessToken
        data = {
            "clientId": "ding0trlgklqrivkmcjc",
            "clientSecret": "NwXl3eTb5bx2IDiTeUklPWMRPNHwVF-sALWJx8tat2-tkkafxrUr6r2DD8g-xlo9",
            "code": authCode,
            "grantType": "authorization_code"
        }
        resp = requests.post('https://api.dingtalk.com/v1.0/oauth2/userAccessToken', json=data).json()
        accessToken = resp.get('accessToken')

        # 根据accessToken获取用户信息
        headers = {"x-acs-dingtalk-access-token": accessToken}
        resp = requests.get('https://api.dingtalk.com/v1.0/contact/users/me', headers=headers).json()

        name = resp.get('nick')
        uid = resp.get('openId')
        phone = resp.get('mobile')
        print(name,uid,phone)
        print('这是uid',uid)

        # 登录，写入三方登录表和用户表
        sfl = User.objects.filter(uid=uuid).first()
        if not sfl:
            # 写入用户表
            # 手机号用户存在直接绑定,不存在注册新用户
            user = User.objects.filter(mobile=phone).first()
            if not user:
                userinfo = {
                    "name": name,
                    "mobile": phone,
                    "password": phone,
                    # "username": phone
                }
                print('2222222222222222222')
                us = UserSer(data=userinfo)
                if us.is_valid():
                    user = us.save()
                else:
                    print('333333333333333333333')
                    return Response({"code": 10001, "msg": str(us.errors)})
            # 写入三方登录表
            sfinfo = {
                "login_type": 1,
                "token": accessToken,
                "uid": uid,
                "user": user.id
            }
            sfs = ThirdLoginSer(data=sfinfo)
            if sfs.is_valid():
                sfs.save()
            else:
                return Response({"code": 10002, "msg": str(sfs.errors)})
        else:
            user = sfl
            sfl.token = accessToken
            sfl.save()
        from tools.myjwtoken import myjwt
        # 生成jwt token并返回前端
        payload = {"userid": user.id, "username": user.name, "exp": int(time.time()) + 60 * 60 * 2}
        print('payload------------------id',payload['userid'])
        token = myjwt.jwt_encode(payload)
        payload["exp"] = int(time.time() + 60 * 60 * 24 * 2)
        refreshToken = myjwt.jwt_encode(payload)
        query = [f"userid={payload['userid']}", f"username={payload['username']}", f"token={token}",
                 f"refreshToken={refreshToken}"]
        return HttpResponseRedirect(f'http://localhost')#:8080/#/login?{"&".join(query)}